//package com.ruoyi.framework.interceptor;
//
//import com.ruoyi.common.utils.StringUtils;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Component;
//import org.springframework.web.servlet.HandlerInterceptor;
//import lombok.extern.slf4j.Slf4j;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//
//@Slf4j
//@Component
//public class IPWhitelistInterceptor implements HandlerInterceptor {
//
//    @Value("${third.party.allowed.ip:81.70.210.5}")
//    private String allowedIp;
//
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        // 获取客户端IP地址
//        String clientIp = getClientIp(request);
//
//        // 检查是否为允许的IP
//        if (!isIpAllowed(clientIp)) {
//            log.warn("来自非法IP的访问尝试：{}", clientIp);
//            handleUnauthorizedAccess(response);
//            return false;
//        }
//
//        return true;
//    }
//
//    /**
//     * 获取客户端真实IP地址
//     */
//    private String getClientIp(HttpServletRequest request) {
//        String ip = request.getHeader("X-Forwarded-For");
//        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("Proxy-Client-IP");
//        }
//        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
//            ip = request.getRemoteAddr();
//        }
//        return ip;
//    }
//
//    /**
//     * 检查IP是否在白名单中
//     */
//    private boolean isIpAllowed(String clientIp) {
//        // 精确匹配或支持通配符匹配
//        return allowedIp.equals(clientIp) ||
//               (allowedIp.endsWith("*") && clientIp.startsWith(allowedIp.substring(0, allowedIp.length() - 1)));
//    }
//
//    /**
//     * 处理未授权访问
//     */
//    private void handleUnauthorizedAccess(HttpServletResponse response) throws IOException {
//        response.setContentType("application/json;charset=UTF-8");
//        response.setStatus(403);
//        response.getWriter().write(
//            "{\"msg\":\"您无权进行数据接入！\",\"code\":403,\"data\":null}"
//        );
//    }
//}